<?php
  require('includes/application_top.php');
  require(DIR_WS_CLASSES . 'currencies.php');
  $currencies = new sccurrencies();
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<script language="javascript" src="includes/general.js"></script>
<script type="text/javascript" src="../js/jquery-1.4.2.js"></script>

<link type="text/css" href="http://jqueryui.com/themes/base/jquery.ui.all.css" rel="stylesheet" />
<script type="text/javascript" src="../js/jquery.ui.core.js"></script>
<script type="text/javascript" src="../js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="../js/jquery.ui.datepicker.js"></script>

<script type="text/javascript">
	jQuery(function() {
		jQuery("#datefrompicker").datepicker({ dateFormat: 'dd/mm/yy' });
        jQuery("#datetopicker").datepicker({ dateFormat: 'dd/mm/yy' });
	});
</script>

</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF" onload="SetFocus();">
<div id="spiffycalendar" class="text"></div>
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2">
  <tr>
    <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="1" cellpadding="1" class="columnLeft">
<!-- left_navigation //-->
<?php require(DIR_WS_INCLUDES . 'column_left.php'); ?>
<!-- left_navigation_eof //-->
    </table></td>
<!-- body_text //-->
<?php
function tep_checkdate($date_to_check, $format_string, &$date_array) {
    $separator_idx = -1;

    $separators = array('-', ' ', '/', '.');
    $month_abbr = array('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec');
    $no_of_days = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

    $format_string = strtolower($format_string);

    if (strlen($date_to_check) != strlen($format_string)) {
      return false;
    }

    $size = sizeof($separators);
    for ($i=0; $i<$size; $i++) {
      $pos_separator = strpos($date_to_check, $separators[$i]);
      if ($pos_separator != false) {
        $date_separator_idx = $i;
        break;
      }
    }

    for ($i=0; $i<$size; $i++) {
      $pos_separator = strpos($format_string, $separators[$i]);
      if ($pos_separator != false) {
        $format_separator_idx = $i;
        break;
      }
    }

    if ($date_separator_idx != $format_separator_idx) {
      return false;
    }

    if ($date_separator_idx != -1) {
      $format_string_array = explode( $separators[$date_separator_idx], $format_string );
      if (sizeof($format_string_array) != 3) {
        return false;
      }

      $date_to_check_array = explode( $separators[$date_separator_idx], $date_to_check );
      if (sizeof($date_to_check_array) != 3) {
        return false;
      }

      $size = sizeof($format_string_array);
      for ($i=0; $i<$size; $i++) {
        if ($format_string_array[$i] == 'mm' || $format_string_array[$i] == 'mmm') $month = $date_to_check_array[$i];
        if ($format_string_array[$i] == 'dd') $day = $date_to_check_array[$i];
        if ( ($format_string_array[$i] == 'yyyy') || ($format_string_array[$i] == 'aaaa') ) $year = $date_to_check_array[$i];
      }
    } else {
      if (strlen($format_string) == 8 || strlen($format_string) == 9) {
        $pos_month = strpos($format_string, 'mmm');
        if ($pos_month != false) {
          $month = substr( $date_to_check, $pos_month, 3 );
          $size = sizeof($month_abbr);
          for ($i=0; $i<$size; $i++) {
            if ($month == $month_abbr[$i]) {
              $month = $i;
              break;
            }
          }
        } else {
          $month = substr($date_to_check, strpos($format_string, 'mm'), 2);
        }
      } else {
        return false;
      }

      $day = substr($date_to_check, strpos($format_string, 'dd'), 2);
      $year = substr($date_to_check, strpos($format_string, 'yyyy'), 4);
    }

    if (strlen($year) != 4) {
      return false;
    }

    if (!settype($year, 'integer') || !settype($month, 'integer') || !settype($day, 'integer')) {
      return false;
    }

    if ($month > 12 || $month < 1) {
      return false;
    }

    if ($day < 1) {
      return false;
    }

    if (tep_is_leap_year($year)) {
      $no_of_days[1] = 29;
    }

    if ($day > $no_of_days[$month - 1]) {
      return false;
    }

    $date_array = array($year, $month, $day);

    return true;
  }
  
  function tep_is_leap_year($year) {
    if ($year % 100 == 0) {
      if ($year % 400 == 0) return true;
    } else {
      if (($year % 4) == 0) return true;
    }

    return false;
  }
function tep_p_stats($raw_date,$type) {
    if ( ($raw_date == '0000-00-00 00:00:00') || empty($raw_date) ) return false;
    if($type == 'd'){
        $date = (int)substr($raw_date, 8, 2);
    }
    if($type == 'm'){
        $date = (int)substr($raw_date, 5, 2);
    }    
    if($type == 'y'){
        $date = substr($raw_date, 0, 4);
    }
    
    return $date;        
}
$day = $HTTP_POST_VARS['day'];
$month = $HTTP_POST_VARS['month'];
    // Lấy sum đơn đặt hàng
    $sum_orders_query = tep_db_query("select count(*) as total from orders_new");
    $sum_orders = tep_db_fetch_array($sum_orders_query);
        
    // Lấy sum sản phẩm đặt hàng
    $sum_orders_product_query = tep_db_query("select count(*) as total from orders_new_product");
    $sum_orders_product = tep_db_fetch_array($sum_orders_product_query);
        
    // Lấy sum khách hàng đặt hàng
    $sum_orders_cus_query = tep_db_query("select count(customers_id) as total from orders_new");
    $sum_orders_cus = tep_db_fetch_array($sum_orders_cus_query);
        
?>
<td width="100%" valign="top">
    <form name="search_stats" action="orders_product_stats.php" method="post">
    <table border="0" width="100%" cellspacing="0" cellpadding="2">
      <tr>
        <td>
        <table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td class="pageHeading">Thống kê đặt hàng</td>
            <td class="dataTableContent" valign="justify">
                <table border="0" width="350px" cellspacing="2" cellpadding="2">
                <tr>
                    <td class="dataTableContent"><?php echo tep_draw_checkbox_field('inorders').'Theo đơn hàng '; ?></td>
                    <td><?php                        
                        $day_array = array();
                        $day_array[] = array('id' => '', 'text' => 'Thống kê theo ngày:&nbsp;');
                        for($i=1;$i<=31;$i++){
                            $day_array[] = array('id' => $i, 'text' => 'Ngày '.$i);
                        }
                        echo tep_draw_pull_down_menu('day', $day_array)
                    ?></td>
                </tr>
                <tr>
                    <td class="dataTableContent"><?php echo tep_draw_checkbox_field('inproducts').'Theo sản phẩm '; ?></td>                                
                    <td><?php                        
                        $month_array = array();
                        $month_array[] = array('id' => '', 'text' => 'Thống kê theo tháng:');
                        for($i=1;$i<=12;$i++){
                            $month_array[] = array('id' => $i, 'text' => 'Tháng '.$i);
                        }
                        echo tep_draw_pull_down_menu('month', $month_array)
                    ?></td>                
                </tr>
                <tr>
                    <td class="dataTableContent">Từ ngày: <?php echo tep_draw_input_field('datefrompicker','',' id="datefrompicker" style="width: 87px;"'); ?></td>
                    <td class="dataTableContent">Đến ngày: <?php echo tep_draw_input_field('datetopicker','',' id="datetopicker" style="width: 87px;"'); ?></td>
                </tr>
                <tr>
                    <td>
                        <?php
                          $status_array = array();
                          $status_array[] = array('id' => '', 'text' => 'Trạng thái đơn hàng');
                          $orders_status1_query = tep_db_query("select * from orders_new_status where published = 1");
                          while ($orders_status1 = tep_db_fetch_array($orders_status1_query)) {
                            $status_array[] = array('id' => $orders_status1['status_id'], 'text' => $orders_status1['status_name']);
                          }                          
                          echo tep_draw_pull_down_menu('status_orders', $status_array);
                        ?>
                    </td>
                    <td><?php echo tep_image_submit('button_stats.gif', 'Thống kê'); ?></td>                
                </tr>
                </table>
            </td>
            <td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td>
          </tr>
        </table>
        </td>
      </tr>
      <tr>
        <td>
            <table border="0" cellpadding="2" cellspacing="2" width="100%">
              <tr bgcolor="#EFEFEF">
                <td class="dataTableContent" align="center" style="font-weight: bold;">Tổng đơn đặt hàng</td>
                <td class="dataTableContent" align="center" style="font-weight: bold;">Tổng sản phẩm đặt hàng</td>
                <td class="dataTableContent" align="center" style="font-weight: bold;">Tổng số khách</td>
              </tr>
              <tr>
                <td class="dataTableContent" align="center"><?php echo $sum_orders['total']; ?></td>
                <td class="dataTableContent" align="center"><?php echo $sum_orders_product['total']; ?></td>
                <td class="dataTableContent" align="center">
                    <?php
                        if($sum_orders_cus['total']){
                            echo $sum_orders_cus['total'];
                        }else{ echo "Chưa có khách hàng đặt hàng."; } 
                    ?>
                </td>
              </tr>
            </table>
        </td>        
      </tr>
      
      <tr><td valign="top">
      <!-- Từ ngày đến ngày -->
      <?php
        $dfrom = $HTTP_POST_VARS['datefrompicker'];
        $dto = $HTTP_POST_VARS['datetopicker'];
        $date_check_error = false;
        if (tep_not_null($dfrom)) {
          if (!tep_checkdate($dfrom, DOB_FORMAT_STRING, $dfrom_array)) {
            $error = true;
            $date_check_error = true;
          }
        }    
        if (tep_not_null($dto)) {
          if (!tep_checkdate($dto, DOB_FORMAT_STRING, $dto_array)) {
            $error = true;
            $date_check_error = true;
          }
        }
        if (($date_check_error == false) && tep_not_null($dfrom) && tep_not_null($dto)) {
          if (mktime(0, 0, 0, $dfrom_array[1], $dfrom_array[2], $dfrom_array[0]) > mktime(0, 0, 0, $dto_array[1], $dto_array[2], $dto_array[0])) {
            $error = true;
          }
        }
        if($error == true){
            echo '<table border="0" width="100%" cellspacing="0" cellpadding="0">
                      <tr>
                        <td class="pageHeading"><br />Đơn đặt hàng</td>
                      </tr>
                  </table>
                  <table border="0" width="100%" cellspacing="0" cellpadding="0">
                  <tr>
                    <td class="dataTableContent" align="center" style="color:red;">Ngày bắt đầu không thể nhỏ hơn ngày đến.</td>                    
                 </tr>
                 </table>
            ';
        }else{
            if($dfrom && $dto){
                $sum_orders_df_dt_query = tep_db_query("select * from orders_new where created >= '".tep_date_raw($dfrom)."' and created <= '".tep_date_raw($dto)."'");
                $sum_orders_df_dt_test_query = tep_db_query("select * from orders_new where created >= '".tep_date_raw($dfrom)."' and created <= '".tep_date_raw($dto)."'");
            }elseif($dfrom){
                $sum_orders_df_dt_query = tep_db_query("select * from orders_new where created >= '".tep_date_raw($dfrom)."'");
                $sum_orders_df_dt_test_query = tep_db_query("select * from orders_new where created >= '".tep_date_raw($dfrom)."'");
            }elseif($dto){
                $sum_orders_df_dt_query = tep_db_query("select * from orders_new where created <= '".tep_date_raw($dto)."'");
                $sum_orders_df_dt_test_query = tep_db_query("select * from orders_new where created <= '".tep_date_raw($dto)."'");
            }else{
                $sum_orders_df_dt_query = tep_db_query("select * from orders_new where created >= '".tep_date_raw($dfrom)."' and created <= '".tep_date_raw($dto)."'");
                $sum_orders_df_dt_test_query = tep_db_query("select * from orders_new where created >= '".tep_date_raw($dfrom)."' and created <= '".tep_date_raw($dto)."'");
            }            
            
            $sum_orders_df_dt_test = tep_db_fetch_array($sum_orders_df_dt_test_query);
            if($sum_orders_df_dt_test){
                echo '<table border="0" width="100%" cellspacing="0" cellpadding="0">
                          <tr>
                            <td class="pageHeading"><br />Đơn đặt hàng<br /><br /></td>
                          </tr>
                      </table>
                      <table border="0" width="100%" cellspacing="0" cellpadding="2">
                      <tr class="dataTableHeadingRow">
                        <td class="dataTableHeadingContent">Khách hàng</td>
                        <td class="dataTableHeadingContent">Ngày đặt</td>
                        <td class="dataTableHeadingContent">Tổng tiền</td>
                        <td class="dataTableHeadingContent">Tiền đặt cọc</td>
                        <td class="dataTableHeadingContent">Tiền còn lại</td>
                        <td class="dataTableHeadingContent">Trạng thái</td>
                      </tr>                      
                    ';                  
                while($sum_orders_df_dt = tep_db_fetch_array($sum_orders_df_dt_query)){
                    $account_query = tep_db_query("select * from " . TABLE_CUSTOMERS . " where customers_id = '" . $sum_orders_df_dt['customers_id'] . "'");
                    $account = tep_db_fetch_array($account_query);                
                    $orders_status_query = tep_db_query("select * from orders_new_status where status_id = '" . $sum_orders_df_dt['status_id'] . "'");
                    $orders_status = tep_db_fetch_array($orders_status_query);
                    
                    $price_reply = explode(',', $sum_orders_df_dt['price_reply']);
                    $sum_price1 = array_sum($price_reply) + $sum_orders_df_dt['tax_reply'] + $sum_orders_df_dt['ship_reply'];                
                    if($sum_orders_df_dt['currency_reply']=='USD'){
                        $sum_price = $sum_price1.' '.$sum_orders_df_dt['currency_reply'];
                        $tienconlai = $sum_price1 - $sum_orders_df_dt['deposit'].' '.$sum_orders_df_dt['currency_reply'];                
                    }else{
                        $sum_price = $currencies->display_price($sum_price1);
                        $tienconlai = $currencies->display_price($sum_price1 - $sum_orders_df_dt['deposit']);
                    }
                    ?>
                    <tr>
                        <td class="dataTableContent"><?php echo ''.$account['customers_firstname'].' '.$account['customers_lastname']; ?></td>
                        <td class="dataTableContent"><?php echo $sum_orders_df_dt['created']; ?></td>
                        <td class="dataTableContent"><?php echo $sum_price; ?></td>
                        <td class="dataTableContent">
                        <?php 
                        if($sum_orders_df_dt['currency'] == 'VND'){ 
                            $currencies->display_price($sum_orders_df_dt['deposit']);
                        }else{echo $sum_orders_df_dt['deposit'].' '.$sum_orders_df_dt['currency'];}
                        ?>
                        </td>
                        <td class="dataTableContent"><?php echo $tienconlai; ?></td>
                        <td class="dataTableContent"><?php echo $orders_status['status_name']; ?></td>
                    </tr>
                    <?php
                }
                echo '</table>';    
            }                        
        }
      ?>
      <?php
      $inorders = $HTTP_POST_VARS['inorders'];
      $inproducts = $HTTP_POST_VARS['inproducts'];
      $status_orders = $HTTP_POST_VARS['status_orders'];
      
      if($status_orders){
        $sum_orders_m_all_query = tep_db_query("select * from orders_new where status_id=".$status_orders);
      }else{
        $sum_orders_m_all_query = tep_db_query("select * from orders_new");  
      }
      
      if($day || $month || $status_orders || $inorders || $inproducts){
        if($inproducts){
            echo '<table border="0" width="100%" cellspacing="0" cellpadding="2">';
        }else{
            echo '<table border="0" width="100%" cellspacing="0" cellpadding="2">
                  <tr class="dataTableHeadingRow">
                    <td class="dataTableHeadingContent">Số</td>
                    <td class="dataTableHeadingContent">Khách hàng</td>
                    <td class="dataTableHeadingContent">Ngày đặt</td>
                    <td class="dataTableHeadingContent">Tổng tiền</td>
                    <td class="dataTableHeadingContent">Tiền đặt cọc</td>
                    <td class="dataTableHeadingContent">Tiền còn lại</td>
                    <td class="dataTableHeadingContent">Trạng thái</td>
                  </tr>';
        }
        while($sum_orders_m_all = tep_db_fetch_array($sum_orders_m_all_query)){
            if($day && $month){
                $now_d_m = $month;
                $now_d_m_db = tep_p_stats($sum_orders_m_all['created'],'m');
            }
            elseif($day){
                //$now_d_m = date('j');
                $now_d_m = $day;
                $now_d_m_db = tep_p_stats($sum_orders_m_all['created'],'d');
            }elseif($month){
                $now_d_m = $month;
                $now_d_m_db = tep_p_stats($sum_orders_m_all['created'],'m');
            }                            
            if($now_d_m_db == $now_d_m){
                $sum_orders_d_query = tep_db_query("select * from orders_new where created = '".$sum_orders_m_all['created']."'");
                $sum_orders_d = tep_db_fetch_array($sum_orders_d_query);
                
                $account_query = tep_db_query("select * from " . TABLE_CUSTOMERS . " where customers_id = '" . $sum_orders_d['customers_id'] . "'");
                $account = tep_db_fetch_array($account_query);                
                $orders_status_query = tep_db_query("select * from orders_new_status where status_id = '" . $sum_orders_d['status_id'] . "'");
                $orders_status = tep_db_fetch_array($orders_status_query);
                
                $price_reply = explode(',', $sum_orders_d['price_reply']);
                $sum_price1 = array_sum($price_reply) + $sum_orders_d['tax_reply'] + $sum_orders_d['ship_reply'];                
                if($sum_orders_m_all['currency_reply']=='USD'){
                    $sum_price = $sum_price1.' '.$sum_orders_d['currency_reply'];
                    $tienconlai = $sum_price1 - $sum_orders_d['deposit'].' '.$sum_orders_d['currency_reply'];                
                }else{
                    $sum_price = $currencies->display_price($sum_price1);
                    $tienconlai = $currencies->display_price($sum_price1 - $sum_orders_d['deposit']);
                }
                if($inproducts){
                    echo '<tr><td></td><td colspan="6" class="dataTableContent"><b>Đơn hàng '.$sum_orders_d['orders_id'].'</b></td></tr>';
                }else{                
                ?>
                <tr style="font-weight: bold;">
                    <td class="dataTableContent"><?php echo $sum_orders_d['orders_id']; ?></td>
                    <td class="dataTableContent"><?php echo ''.$account['customers_firstname'].' '.$account['customers_lastname']; ?></td>
                    <td class="dataTableContent"><?php echo $sum_orders_d['created']; ?></td>
                    <td class="dataTableContent"><?php echo $sum_price; ?></td>
                    <td class="dataTableContent">
                    <?php 
                    if($sum_orders_d['currency'] == 'VND'){ 
                        echo $currencies->display_price($sum_orders_d['deposit']);
                    }else{echo $sum_orders_d['deposit'].' '.$sum_orders_d['currency'];}
                    ?>
                    </td>
                    <td class="dataTableContent"><?php echo $tienconlai; ?></td>
                    <td class="dataTableContent"><?php echo $orders_status['status_name']; ?></td>
                </tr>
                <?php } if($inorders){}else{ ?>
                <tr><td></td><td colspan="6" class="dataTableContent">
                <table border="0" cellpadding="2" cellspacing="2" width="100%">
                  <tr bgcolor="#EFEFEF">
                    <td class="dataTableContent" align="center" style="font-weight: bold;">STT</td>
                    <td class="dataTableContent" align="center" style="font-weight: bold;">Hình ảnh</td>
                    <td class="dataTableContent" align="center" style="font-weight: bold;">Số lượng</td>
                    <td class="dataTableContent" align="center" style="font-weight: bold;">Liên kết</td>
                    <td class="dataTableContent" align="center" style="font-weight: bold;">Giá</td>
                    <td class="dataTableContent" align="center" style="font-weight: bold;">Mô tả</td>
                  </tr>
                <?php
                    $sum_orders_product_d_query = tep_db_query("select * from orders_new_product where orders_id = '".$sum_orders_d['orders_id']."'");
                    while($sum_orders_product_d = tep_db_fetch_array($sum_orders_product_d_query)){
                        if($sum_orders_product_d['currency'] == 'VND'){ 
                            $product_price = $currencies->display_price($sum_orders_product_d['price'], tep_get_tax_rate($sum_orders_product_d['products_tax_class_id']));
                        }else{
                            $product_price = $sum_orders_product_d['price'].' '.$sum_orders_product_d['currency'];
                        }
                        if($sum_orders_product_d['images_url']){
                            $images_url = '<img src="'. $sum_orders_product_d['images_url'] .'" width="40px" />';
                        }else{
                            $images_url = '';
                        }
                        echo '<tr>
                            <td class="dataTableContent" align="center">'. $sum_orders_product_d['orders_product_id'] .'</td>
                            <td class="dataTableContent" align="center">'.$images_url.'</td>
                            <td class="dataTableContent" align="center">'. $sum_orders_product_d['quanlity'] .'</td>
                            <td class="dataTableContent" align="left">'. $sum_orders_product_d['weblink'] .'</td>
                            <td class="dataTableContent" align="center">'. $product_price .'</td>
                            <td class="dataTableContent" align="center">'. $sum_orders_product_d['description'] .'</td>
                         </tr>';
                    }
                ?>
                </table>                          
                </td></tr>
                <?php
                }
            }    
        }
        echo '</table>';
      }  
      ?>
      </td></tr>
    </table>
    </form>      
</td>
<!-- body_text_eof //-->
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
<br>
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
